import { envConfig } from './env'
const defaultAppId = envConfig.appId
const defaultTenantId = envConfig.tenantId
const defaultWxAppId = envConfig.wxAppId
const CODE_SUCCESS = 0

export default async function request(url, options={}) {
  const { payload, method = 'GET', showToast = true, autoLogin = true } = options
  const token = uni.getStorageSync('dp_token')
  const header = token ? { Authorization: `${token}` } : {}
  if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
    header['content-type'] = 'application/json'
  }
  const channelId = uni.getStorageSync('channelId') || ''
  let [error, res] = await uni.request({
    url,
    method,
    data: {
      appId: defaultAppId,
      tenantId: defaultTenantId,
      wxAppId: defaultWxAppId,
      channelId,
      ...payload,
    },
    header,
    timeout: 10000
  });
  return handleResult({ error, res, url, options, method });
}

// 处理请求结果
const handleResult = ({ error, res, url, options, method, filePath, name, formData }) => {
  if (error) {
    uni.showToast({ title: "数据请求失败", duration: 3000, icon: "none" });
    return false;
  }
  const { code } = res.data
  if (Number(code) !== CODE_SUCCESS) {
    if(Number(res.statusCode) === 400) {
      uni.showToast({ title: res.data.msg, duration: 3000, icon: "none" });
      return Promise.reject()
    }
    if(Number(code) === 401) {
      uni.removeStorageSync("dp_token");
      let logining = uni.getStorageSync("logining");
      if (logining) {
        return false;
      }
      uni.setStorageSync("logining", true);
      uni.navigateTo({
        url: "/pages/login/index",
      });
      return false;
    }
    // if(Number(code) === 400) {
    //   if(res.data.msg.indexOf('该会员不存在') > -1) {
    //     uni.navigateTo({ url: "/pages/login/index" });
    //     return Promise.reject()
    //   }
    // }
    uni.showToast({ title: res.data.msg || '接口异常', duration: 3000, icon: "none", mask: true });
    return Promise.reject(res)
  }
  return Promise.resolve(res.data)
};
